package com.leizi.igym.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leizi.igym.constant.CourseConstant;
import com.leizi.igym.domain.Course;
import com.leizi.igym.dto.*;
import com.leizi.igym.enums.FileUploadBizEnum;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.manager.CosManager;
import com.leizi.igym.resp.PageResult;
import com.leizi.igym.resp.Result;
import com.leizi.igym.service.CourseService;
import com.leizi.igym.utils.COSUtils;
import com.leizi.igym.utils.ThrowUtils;
import com.leizi.igym.vo.CourseVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-05  17:48
 * @Description:
 */

@RestController("adminCourseController")
@RequestMapping("/admin/course")
@Tag(name = "管理端-课程相关接口")
@Slf4j
public class CourseController {

    @Resource
    private CourseService courseService;

    @Resource
    private CosManager cosManager;

    @Operation(summary = "管理端：新增课程信息")
    @PostMapping
    public Result add(@RequestBody CourseAddDTO dto) {
        log.info("管理端正在添加课程信息，课程信息为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        boolean result = courseService.saveInAdmin(dto);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.OPERATION_ERROR, "添加课程失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：删除课程信息")
    @DeleteMapping("{id}")
    public Result deleteCourse(@PathVariable("id") Long id) {
        log.info("管理端正在删除课程信息，课程id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0, ReturnCodeEnum.PARAMS_ERROR);
        boolean result = courseService.deleteTrainerInAdmin(id);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除教练信息失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：批量删除课程信息")
    @DeleteMapping("batch")
    public Result deleteBatch(@RequestBody List<Long> ids) {
        log.info("管理端正在批量删除课程信息，课程们的id为：{}", ids);
        ThrowUtils.throwIf(CollectionUtil.isEmpty(ids), ReturnCodeEnum.PARAMS_ERROR);
        boolean result = courseService.deleteTrainerBatchInAdmin(ids);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除教练信息失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：修改课程信息")
    @PutMapping("{id}")
    public Result modifyCourse(@PathVariable("id") Long id, @RequestBody CourseDTO dto) {
        log.info("管理端正在修改课程信息，id为：{}，修改课程为：{}", id, dto);
        ThrowUtils.throwIf(Objects.isNull(dto) ||
                        id == null ||
                        id <= 0 ||
                        !id.equals(dto.getId()),
                ReturnCodeEnum.PARAMS_ERROR);
        Course dbCourse = courseService.getById(id);
        String dbTCourseCover = dbCourse.getCover();
        String cover = dto.getCover();
        if (dbTCourseCover.contains(FileUploadBizEnum.TRAINER_AVATAR.getValue()) &&
                !cover.equals(dbTCourseCover)) {
            cosManager.deleteObject(COSUtils.parseFileName(FileUploadBizEnum.COURSE_COVER,dbTCourseCover));
        }
        boolean result = courseService.updateInAdmin(dto);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "修改教练信息失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：分页查询课程信息")
    @GetMapping("page")
    public Result<PageResult> getCoursePage(CoursePageQueryDTO dto) {
        log.info("管理端正在分页查询课程信息，查询参数为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);

        long current = dto.getCurrent();
        long size = dto.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 50 || current <= 0 || size <= 0, ReturnCodeEnum.PARAMS_ERROR);
        Page<CourseVO> page = courseService.getVOPage(dto);
        return page == null ? Result.ok(PageResult.builder()
                .records(Collections.emptyList())
                .total(0)
                .build()) : Result.ok(PageResult.builder()
                .records(page.getRecords())
                .total(page.getTotal())
                .build());
    }

    @Operation(summary = "管理端：根据id查询课程信息")
    @GetMapping("{id}")
    public Result<CourseVO> getById(@PathVariable("id") Long id) {
        log.info("管理端正在根据id查询课程信息，id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0,
                ReturnCodeEnum.PARAMS_ERROR);

        CourseVO courseVO = courseService.getVOById(id);
        if (Objects.isNull(courseVO)) {
            throw new BusinessException(ReturnCodeEnum.NOT_FOUND_ERROR, "该教练信息不存在！");
        }

        return Result.ok(courseVO);
    }

    @Operation(summary = "管理端：修改课程状态")
    @PutMapping("/{id}/{status}")
    public Result<Boolean> identify(@PathVariable("id") Long id,
                                    @PathVariable("status") Integer status) {
        log.info("管理端正在修改课程状态，课程id：{}", id);

        // 校验参数id是否合法
        ThrowUtils.throwIf(Objects.isNull(id) || id < 0, ReturnCodeEnum.PARAMS_ERROR, "课程id有误！");

        // 校验isIdentify参数是否合法
        ThrowUtils.throwIf(Objects.isNull(status) ||
                        !CourseConstant.COURSE_STATUS_LIST.contains(status)
                , ReturnCodeEnum.PARAMS_ERROR, "认证参数有误！");
        boolean result = courseService.changeStatus(id, status);
        return Result.ok(result);
    }


}
